package com.tzf.reggie.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tzf.reggie.common.R;
import com.tzf.reggie.dto.OrdersDto;
import com.tzf.reggie.entity.OrderDetail;
import com.tzf.reggie.entity.Orders;
import com.tzf.reggie.service.OrderDetailService;
import com.tzf.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {

    @Autowired
    private OrderService orderService;

    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 用户下单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R<String> submit(@RequestBody Orders orders){
        log.info("订单数据：{}",orders);
        orderService.submit(orders);
        return R.success("下单成功");
    }

    /**
     * 移动端订单分页展示（最新订单功能，历史订单功能）
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R<Page> pageR(Integer page, Integer pageSize){
        Page<OrdersDto> ordersDto = orderService.showPage(page,pageSize);
        return R.success(ordersDto);
    }

    /**
     * 客户端订单分页查询（包含订单号，日期筛选）
     * @param page
     * @param pageSize
     * @param number
     * @param beginTime
     * @param endTime
     * @return
     */
    @GetMapping("/page")
    public R<Page> page(int page, int pageSize, Long number, String beginTime, String endTime){
        Page<Orders> page1 = new Page<>(page, pageSize);
        LocalDateTime begin = null;
        LocalDateTime end = null;
        if (beginTime != null || endTime!=null) {
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            begin = LocalDateTime.parse(beginTime, formatter);
            end = LocalDateTime.parse(endTime, formatter);
        }
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(number != null ,Orders::getNumber,number);
        wrapper.gt(begin != null,Orders::getOrderTime,begin).lt(end!=null,Orders::getOrderTime,end);
        wrapper.orderByDesc(Orders::getOrderTime);

        List<Orders> list = orderService.list(wrapper);
//        log.info(list.toString());
        Page<Orders> page2 = orderService.page(page1, wrapper);
        page2.setRecords(list);
        return R.success(page2);
    }

    /**
     * 派送功能（状态修改为3）
     * @param orders
     * @return
     */
    @PutMapping
    public R<String> deliver(@RequestBody Orders orders){
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getId,orders.getId());
        Orders orders1 = orderService.getOne(wrapper);
        orders1.setStatus(orders.getStatus());
        orderService.updateById(orders1);
        return R.success("设置成功！");
    }

    /**
     * 再来一单
     * @param order
     * @return
     */
    @PostMapping("/again")
    public R<Orders> again(@RequestBody Orders order){
        LambdaQueryWrapper<OrderDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(OrderDetail::getOrderId,order.getId());
        List<OrderDetail> list = orderDetailService.list(wrapper);
        long ordersId = IdWorker.getId();
        Orders order1 = orderService.getById(order.getId());
        Orders orders = new Orders();
        BeanUtils.copyProperties(order1,orders,"id,number,orderTime,checkoutTime,status");
        orders.setId(ordersId);
        orders.setNumber(String.valueOf(ordersId));
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setStatus(2);
        List<OrderDetail> orderDetails = list.stream().map((item) -> {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(item,orderDetail,"id");
            orderDetail.setOrderId(ordersId);
            return orderDetail;
        }).collect(Collectors.toList());
        orderService.save(orders);
        orderDetailService.saveBatch(orderDetails);
        return R.success(orders);
    }
}